package com.faiz.example.springtest.dao.mapper.typehandler;

import com.faiz.example.springtest.entity.Student;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({Student.class})
public class StudentTypeHandler extends BaseTypeHandler<Student> {
    private ObjectMapper mapper = new ObjectMapper();
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Student student, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(i, mapper.writeValueAsString(student));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Student getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return get(resultSet.getString(s));
    }

    @Override
    public Student getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return get(resultSet.getString(i));
    }

    @Override
    public Student getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return get(callableStatement.getString(i));
    }

    private Student get(String value) {
        try {
            return mapper.readValue(value, Student.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
